package com.xique.door.project.miniprogram.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.common.core.web.domain.PageResult;
import com.xique.door.project.miniprogram.bean.domian.Car;
import com.xique.door.project.miniprogram.bean.vo.MiniCarVO;
import com.xique.door.project.miniprogram.service.IMiniCarService;
import com.xique.door.project.miniprogram.mapper.MiniCarMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MiniCarServiceImpl extends ServiceImpl<MiniCarMapper, Car> implements IMiniCarService {

  @Override
  public AjaxResult insertMiniCar(Car car) {
    car.setCreateTime(new Date());
    car.setUpdateTime(new Date());
    car.setDel(0);
    int rep = baseMapper.insert(car);
    if (rep > 0) {
      return AjaxResult.success();
    }
    return AjaxResult.error("添加失败");
  }

  @Override
  public AjaxResult getdeleteCar(Long id) {
    Car car = new Car();
    car.setId(id);
    car.setUpdateTime(new Date());
    car.setDel(1);
    int rep = baseMapper.updateById(car);
    if (rep > 0) {
      return AjaxResult.success();
    }
    return AjaxResult.error("删除失败");
  }

  @Override
  public AjaxResult updateeCar(Long id,String licensePlate) {
    Car car = new Car();
    car.setId(id);
    car.setLicensePlate(licensePlate);
    car.setUpdateTime(new Date());
    int rep = baseMapper.updateById(car);
    if (rep > 0) {
      return AjaxResult.success();
    }
    return AjaxResult.error("修改失败");
  }

  @Override
  public PageResult getCarList(Long userId, Integer pageNum, Integer pageSize) {
    QueryWrapper<Car> queryWrapper = new QueryWrapper<>();
    if (userId != null) {
      queryWrapper.eq("user_id", userId);
    }
    queryWrapper.eq("del", 0);
    queryWrapper.eq("base_id", SecurityUtils.getBaseUserId());
    Page<Car> page = new Page<>();
    page.setCurrent(pageNum);
    page.setSize(pageSize);
    IPage<Car> list = baseMapper.selectPage(page, queryWrapper);
    List<MiniCarVO> voList = new ArrayList<>();
    if (list.getRecords().size() > 0) {
      for (Car car : list.getRecords()) {
        MiniCarVO vo = new MiniCarVO();
        vo.setId(car.getId());
        vo.setLicensePlate(car.getLicensePlate());
        vo.setUpdateTime(car.getUpdateTime());
        voList.add(vo);
      }
    }
    long totalPages = list.getPages();
    long totalSize = list.getTotal();
    return PageResult.builder()
        .pageNum(pageNum)
        .pageSize(pageSize)
        .totalPages(totalPages)
        .totalSize(totalSize)
        .list(voList)
        .build();
  }
}
